package cn.xxd;

import cn.util.SolrUtil;
import cn.xxd.entity.XxdItem;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class SolrController {

    @Autowired
    private SolrClient client;

    @Value("${CAERTURL}")
    private String CAERTURL;

    @Value("${SSOURL}")
    private String SSOURL;

    @Value("${SEARCHURL}")
    private String SEARCHURL;

    @Value("${HOMEURL}")
    private String HOMEURL;


    /**
     * 1、增
     *
     * @param message
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    @PostMapping("/insert")
    public String insert(String message) throws IOException, SolrServerException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String dateString = sdf.format(new Date());
        try {
            SolrInputDocument doc = new SolrInputDocument();
            doc.setField("id", dateString);
            doc.setField("text", message);

            /*
             * 如果 spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 collection1 这个参数 下面都是一样的 即
             * client.commit();
             */

            client.add("xxd_solr", doc);
            client.commit("xxd_solr");
            return dateString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 2、查 id
     *
     * @param id
     * @return
     * @throws SolrServerException
     * @throws IOException
     */
    @GetMapping("/get/{id}")
    public String getDocumentById(@PathVariable String id) throws SolrServerException, IOException {
        SolrDocument document = client.getById("xxd_solr", id);
        System.out.println(document);
        //数组类型
        //ArrayList<Student> students = JSON.parseObject(JSON_ARRAY_STR,new TypeReference<ArrayList<Student>>() {})
        //SolrUtil.toBeanList(document,XxdItem.class);
        XxdItem x = (XxdItem) SolrUtil.toBean(document, XxdItem.class);

        return x.toString();
    }

    /**
     * 3、删 id
     *
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public String getAllDocuments(@PathVariable String id) {
        try {
            client.deleteById("xxd_solr", id);
            client.commit("xxd_solr");
            return id;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 4、删 all
     *
     * @return
     */
    @DeleteMapping("deleteAll")
    public String deleteAll() {
        try {

            client.deleteByQuery("xxd_solr", "*:*");
            client.commit("xxd_solr");
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 5、改
     *
     * @param message
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    @PutMapping("/update")
    public String update(String id, String message) throws IOException, SolrServerException {
        try {
            SolrInputDocument doc = new SolrInputDocument();
            doc.setField("id", id);
            doc.setField("text", message);

            /*
             * 如果 spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 xxd_solr 这个参数 下面都是一样的 即
             * client.commit();
             */
            client.add("xxd_solr", doc);
            client.commit("xxd_solr");
            return doc.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 6、全
     *
     * @return
     * @throws SolrServerException
     * @throws IOException
     */
    @GetMapping("/get/all")
    public Map<String, Object> getAll()
            throws SolrServerException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }

    /**
     * 7、查  ++:关键字、高亮、分页  ✔
     *
     * @return
     * @throws SolrServerException
     * @throws IOException
     */
    @GetMapping("/select/{title}/{page}/{size}")
    public String select(@PathVariable String title, @PathVariable Integer page, @PathVariable Integer size, Model model)
            throws SolrServerException, IOException {

        SolrQuery params = new SolrQuery();

        // 查询条件
        params.set("q", "title:" + title);

        // 排序
        params.addSort("id", SolrQuery.ORDER.desc);
        // 分页
        int cal_page = (page - 1) * size;
        params.setStart(cal_page);
        params.setRows(size);

        // 默认域
        // params.set("df", "text");

        // 只查询指定域
        // params.set("fl", "id,text");

        // 开启高亮
        params.setHighlight(true);
        // 设置前缀
        params.setHighlightSimplePre("<span style='color:red'>");
        // 设置后缀
        params.setHighlightSimplePost("</span>");

        // solr数据库是 xxd_solr
        QueryResponse queryResponse = client.query("xxd_solr", params);
        SolrDocumentList results = queryResponse.getResults();

        //数组类型
        List<XxdItem> list = (List<XxdItem>) SolrUtil.toBeanList(results, XxdItem.class);
        ArrayList<XxdItem> arrayList = new ArrayList<XxdItem>();
        for (XxdItem xxdItem : list) {
            if (xxdItem.getStatus() == 1) {
                arrayList.add(xxdItem);
            }
        }

        // 数量，分页用
//		long total = results.getNumFound();// JS 使用 size=MXA 和 data.length 即可知道长度了（但不合理）

        // 获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
//		Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting();
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("total", total);
//		map.put("data", highlight);
//		return map;
        model.addAttribute("results", arrayList);
        model.addAttribute("title", title);
        model.addAttribute("page", page);
        model.addAttribute("size", size);
        model.addAttribute("CAERTURL", CAERTURL);
        model.addAttribute("SSOURL", SSOURL);
        model.addAttribute("SEARCHURL", SEARCHURL);
        model.addAttribute("HOMEURL", HOMEURL);
        return "shoplist";
    }

}
